package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        List<DishVO> list = dishMapper.pageQuery(dishPageQueryDTO);

        Page<DishVO> page = (Page<DishVO>) list;
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DishDTO dishDTO) {
        try {
            //新增菜品
            Dish dish = new Dish();
            BeanUtils.copyProperties(dishDTO,dish);
            dish.setStatus(StatusConstant.DISABLE);
//            dish.setCreateTime(LocalDateTime.now());
//            dish.setUpdateTime(LocalDateTime.now());
//            dish.setCreateUser(BaseContext.getCurrentId());
//            dish.setUpdateUser(BaseContext.getCurrentId());
            dishMapper.insertDish(dish);

            //插入菜品口味数据
            Long dishId = dish.getId();
            List<DishFlavor> flavors = dishDTO.getFlavors();
            //如果 flavors 不为空，则添加菜品口味数据
            if(flavors != null && flavors.size() > 0){
                flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
                dishFlavorMapper.insertDishFlavor(flavors);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 根据id查询菜品数据和口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdAndDishFlavor(Long id) {
        //先查询菜品数据
        Dish dish = dishMapper.getByIdDish(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);

        //查询菜品口味数据
        List<DishFlavor> flavors = dishFlavorMapper.getByIdDishFlavor(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        //更新菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
//        dish.setUpdateTime(LocalDateTime.now());
//        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);

        //更新口味表
        Long dishId = dishDTO.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            //先删除当前菜品口味数据
            dishFlavorMapper.deleteByDishId(dishId);
            //再重新插入当前菜品口味数据
            flavors.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            dishFlavorMapper.insertDishFlavor(flavors);
        }
    }

    /**
     * 修改菜品起售停售
     * @param status
     * @param id
     */
    @Override
    public void updateStatus(Integer status, Long id) {
        //创建一个菜品对象
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dishMapper.update(dish);
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        //删除菜品表中的数据
        for (Long id : ids) {
            //根据id查找菜品数据
            Dish dish = dishMapper.getByIdDish(id);
            if(dish.getStatus() == StatusConstant.ENABLE){
                //如果菜品是起售状态，则不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
            //判断是否关联了套餐，如果关联了，则不能删除
            if(setmealDishMapper.countByDishId(id) > 0){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
            dishMapper.deleteById(id);
            dishFlavorMapper.deleteByDishId(id);
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {
        return dishMapper.listByCategoryId(categoryId);
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByIdDishFlavor(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;

    }

}
